package cz.martindobias.aladin;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public class AnalyticsTracker {

    private static AnalyticsTracker tracker = null;

    private GoogleAnalyticsTracker googleTracker = null;
    private Context startedFor = null;

    private AnalyticsTracker(Context context) {
        this.googleTracker = GoogleAnalyticsTracker.getInstance();
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo("cz.martindobias.aladin", PackageManager.GET_META_DATA);
            this.googleTracker.setProductVersion(info.versionName, String.valueOf(info.versionCode));
        } catch(PackageManager.NameNotFoundException e) {
            this.googleTracker.setProductVersion("aladin", "unknown");
        }
        this.googleTracker.start("UA-18471192-2", context);
        this.startedFor = context;
    }

    public static AnalyticsTracker getInstance(Context context) {
        if(tracker == null) {
            tracker = new AnalyticsTracker(context);
        }
        return tracker;
    }

    public void free(Context context) {
        this.googleTracker.dispatch();
        if(this.startedFor == context) {
            this.startedFor = null;
            this.googleTracker.stop();
        }
    }

    public void trackPageView(String page) {
        this.googleTracker.trackPageView(page);
    }

    public void trackEvent(String category, String action, String label, int value) {
        this.googleTracker.trackEvent(category, action, label, value);
    }

    public void dispatch() {
        this.googleTracker.dispatch();
    }
}
